/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io;
import java.io.OutputStream;
import java.io.IOException;

import exceptions.WriteStreamException;


/**
 * Composes {@link OutputStream} interface realization with additional ability to get access to a previous written symbol
 */
public class Writer {
    private OutputStream os;
    private int prevSymbol = 0;
    /**
     * Creates a new Writer object with an {@link OutputStream} realization object
     * @param os - input stream, that is the basement of the new object
     */
    public Writer(OutputStream os){
        this.os = os;
    }
    /**
     * Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. 
     * The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.
     * @param b - the byte
     * @throws {@link WriteStreamException} if any of {@link IOException} exceptions happened during the read process
     */
    public void write(int b) throws WriteStreamException{
        try{
            os.write(b);
            prevSymbol = b;
        }
        catch(IOException e){
            throw new WriteStreamException(e.getMessage());
        }
        finally{
            //empty
        }
    }
    /**
     * Writes b.length bytes from the specified byte array to this output stream. 
     * The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length).
     * @param b - the data
     * @throws {@link WriteStreamException} if any of {@link IOException} exceptions happened during the read process
     */
    public void write(byte[] b) throws WriteStreamException{
        try{
            os.write(b);
            prevSymbol = b[b.length - 1];
        }
        catch(IOException e){
            throw new WriteStreamException(e.getMessage());
        }
        finally{
            //empty
        }
    }
    /**
     * @return previous read symbol in the output stream, corresponding current Writer object
     */
    public int getPrev(){
        return prevSymbol;
    }
}
